import RevWorker from './worker.js?sharedworker'

export default class SharedSocket {
  /**
   * 构造函数，传入ws地址
   * @param {*} wsUrl
   */
  constructor(wsUrl) {
    this.worker = new RevWorker()
    // 创建WebSocket连接
    this.worker.port.postMessage({
      type: 'connect',
      message: wsUrl
    })
    this.callback = null
    this.worker.port.onmessage = (e) => {
      if (typeof this.callback === 'function') {
        this.callback(e.data)
      }
    }
    // 页面关闭时，关闭当前页面通道
    window.addEventListener('beforeunload', (event) => {
      this.worker.port.postMessage({
        type: 'close',
        message: ''
      })
    })
  }

  /**
   * 关闭当前页面通道
   */
  close() {
    this.worker.port.postMessage({
      type: 'close',
      message: ''
    })
  }

  /**
   * 发送消息
   * @param {*} msg
   */
  postMessage(msg) {
    this.worker.port.postMessage({ type: 'message', message: msg })
  }

  /**
   * 接收消息
   * @param {*} callback
   */
  onmessage(callback) {
    this.callback = callback
  }
}
